package com.finna.tenant.controller;

import com.finna.common.utils.ResponseResult;
import com.finna.tenant.dto.*;
import com.finna.tenant.dto.AccountDTO.AccountCreateRequest;
import com.finna.tenant.dto.AccountDTO.AccountListRequest;
import com.finna.tenant.dto.AccountDTO.AccountResponse;
import com.finna.tenant.dto.AccountDTO.AccountUpdateRequest;
import com.finna.tenant.service.AccountService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 账号控制器
 */
@RestController
@RequestMapping("/account")
@Tag(name = "账号接口", description = "账号信息相关接口")
public class AccountController {
    
    private static final Logger logger = LoggerFactory.getLogger(AccountController.class);
    
    @Autowired
    private AccountService accountService;
    
    /**
     * 创建账号
     */
    @PostMapping
    @Operation(summary = "创建账号", description = "创建新账号")
    public ResponseResult<AccountResponse> addAccount(
            @Validated @RequestBody AccountCreateRequest request) {
        try {
            AccountResponse response = accountService.create(request);
            logger.info("创建账号成功: accountId={}", response.getId());
            return ResponseResult.success(response);
        } catch (RuntimeException e) {
            logger.error("创建账号失败: {}", e.getMessage());
            return ResponseResult.error(400, "账号创建失败: " + e.getMessage());
        } catch (Exception e) {
            logger.error("创建账号失败: {}", e.getMessage(), e);
            return ResponseResult.error(500, "账号创建失败: " + e.getMessage());
        }
    }
    
    /**
     * 修改账号
     */
    @PutMapping("/{accountId}")
    @Operation(summary = "修改账号", description = "修改账号信息")
    public ResponseResult<AccountResponse> modifyAccount(
            @Parameter(description = "账号ID") @PathVariable Long accountId,
            @RequestBody AccountUpdateRequest request) {
        try {
            AccountResponse response = accountService.update(accountId, request);
            logger.info("修改账号成功: accountId={}", accountId);
            return ResponseResult.success(response);
        } catch (RuntimeException e) {
            logger.error("修改账号失败: accountId={}, error={}", accountId, e.getMessage());
            return ResponseResult.error(404, "账号不存在");
        } catch (Exception e) {
            logger.error("修改账号失败: {}", e.getMessage(), e);
            return ResponseResult.error(500, "账号修改失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除账号
     */
    @DeleteMapping("/{accountId}")
    @Operation(summary = "删除账号", description = "删除账号（软删除）")
    public ResponseResult<Void> deleteAccount(
            @Parameter(description = "账号ID") @PathVariable Long accountId) {
        try {
            accountService.delete(accountId);
            logger.info("删除账号成功: accountId={}", accountId);
            return ResponseResult.success(null);
        } catch (RuntimeException e) {
            logger.error("删除账号失败: accountId={}, error={}", accountId, e.getMessage());
            return ResponseResult.error(404, "账号不存在");
        } catch (Exception e) {
            logger.error("删除账号失败: {}", e.getMessage(), e);
            return ResponseResult.error(500, "账号删除失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取账号详情
     */
    @GetMapping("/{accountId}")
    @Operation(summary = "获取账号详情", description = "根据ID获取账号详细信息")
    public ResponseResult<AccountResponse> accountDetail(
            @Parameter(description = "账号ID") @PathVariable Long accountId) {
        try {
            AccountResponse response = accountService.getById(accountId);
            return ResponseResult.success(response);
        } catch (RuntimeException e) {
            logger.error("查询账号失败: accountId={}, error={}", accountId, e.getMessage());
            return ResponseResult.error(404, "账号不存在");
        } catch (Exception e) {
            logger.error("查询账号失败: {}", e.getMessage(), e);
            return ResponseResult.error(500, "账号查询失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取账号列表（分页）
     */
    @GetMapping
    @Operation(summary = "获取账号列表", description = "分页查询账号列表，支持过滤条件")
    public ResponseResult<PageResponse<AccountResponse>> accountList(
            @Parameter(description = "用户名") @RequestParam(required = false) String name,
            @Parameter(description = "邮箱") @RequestParam(required = false) String email,
            @Parameter(description = "状态") @RequestParam(required = false) Boolean status,
            @Parameter(description = "页码") @RequestParam(required = false, defaultValue = "1") Integer page,
            @Parameter(description = "每页大小") @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        try {
            AccountListRequest request = new AccountListRequest();
            request.setName(name);
            request.setEmail(email);
            request.setStatus(status);
            request.setPage(page);
            request.setPageSize(pageSize);
            
            PageResponse<AccountResponse> response = accountService.list(request);
            logger.info("账号列表查询成功: page={}, pageSize={}, total={}", page, pageSize, response.getTotal());
            
            return ResponseResult.success(response);
        } catch (Exception e) {
            logger.error("账号列表查询失败: {}", e.getMessage(), e);
            return ResponseResult.error(500, "账号列表查询失败: " + e.getMessage());
        }
    }
}

